package ar.org.cfired.creditos.servlets;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.HibernateException;
import org.jbpm.api.*;
import ar.org.cfired.creditos.Solicitud;
/*import java.util.ArrayList;

import ar.org.cfired.creditos.sbsa.JbpmSBA;
import ar.org.cfired.creditos.sbsa.Log;
import ar.org.cfired.creditos.sbsa.FechaActualizacion;*/
import ar.org.cfired.hibernate.utils.HibernateUtil;

public class ServletCopiarSolicitudes extends HttpServlet{
	private static final long serialVersionUID = 1L;

	public void init() throws ServletException {
	    // Initialization here...
	  }
	
	public void service( HttpServletRequest req, HttpServletResponse res ) throws ServletException {
		PrintWriter out = null;
		try {
		out = res.getWriter();

	List<Solicitud> respuesta;
	Transaction tx = null;
	Session session = null;
	Session session2 = null;
	try {
		out.println("Scheduler de Roger - Por iniciar sesion");
		session = HibernateUtil.getSessionFactory().openSession();
		tx = session.beginTransaction();
		out.println("Scheduler de Roger - Transaccion iniciada");
    respuesta = (List<Solicitud>) session.createQuery("from Solicitud where cre_cargado_dprocess=0").list();

    out.println( "Scheduler de Roger -  " + respuesta.size() + " documento(s) nuevo(s)" );
    if (respuesta.size() > 0) {
    	session2 = HibernateUtil.getSessionFactory().openSession();
    }
    String textoFinal = "";
    Map<String,Object> variables;
    ProcessInstance processInstance;
    ExecutionService executionService = new Configuration().buildProcessEngine().getExecutionService();
    Solicitud loadedMsg = null;
    for ( Iterator<Solicitud> iter = respuesta.iterator(); iter.hasNext(); ) {
    	try {
    	session2.beginTransaction();
    	loadedMsg = (Solicitud) iter.next();
        textoFinal += loadedMsg.getCreApoderadoEmail() +  " \n";
      
        variables = loadedMsg.getVariables(session2);
		processInstance = executionService.startProcessInstanceByKey("Creditos", variables);	            
        
		loadedMsg.setCreCargadoDprocess(1);
		session2.update(loadedMsg);
        session2.getTransaction().commit();
    	}
    	catch (HibernateException e) {
    		out.println( "Scheduler de Roger -  No se pudo cargar el documento - Hibernate Exception " + ((loadedMsg!=null)?loadedMsg.getCreId():""));
    		out.println(e.getMessage());
    		CreditosServletWebException e2 = new CreditosServletWebException(e,"al cargar el documento");
			out.print(e2.getMessage());
    	}
    	catch (Exception e) {
    		out.println( "Scheduler de Roger -  No se pudo cargar el documento - Exception " + ((loadedMsg!=null)?loadedMsg.getCreId():""));
    		out.println(e.getMessage());
    		CreditosServletWebException e2 = new CreditosServletWebException(e,"al cargar el documento");
			out.print(e2.getMessage());
    	}
        //System.out.println( loadedMsg );
    }
    
    session.getTransaction().commit();
    out.println(textoFinal);
	} 
	catch (HibernateException e){
		System.out.println("Scheduler de Roger - " + e.getMessage());
		if (tx!=null) 
			if (!tx.wasRolledBack())
				tx.rollback();
		CreditosServletWebException e2 = new CreditosServletWebException(e,"al cargar el documento");
		out.print(e2.getMessage());
		
	}
	catch (Exception e) {
		out.println("Scheduler de Roger - " + e.getMessage());
		CreditosServletWebException e2 = new CreditosServletWebException(e,"al cargar el documento");
		out.print(e2.getMessage());
	}
	finally {
		if (session!=null)
			session.close();
	}
	
	
	out.println("Scheduler de Roger - Terminado en " + new Date());
	}
	catch(IOException e) {
		System.out.println("IOException  " + e.getMessage());
		CreditosServletWebException e2 = new CreditosServletWebException(e,"al cargar el documento");
		out.print(e2.getMessage());
	}
	catch(Exception e) {
		System.out.println("Exception  " + e.getMessage());
		CreditosServletWebException e2 = new CreditosServletWebException(e,"al cargar el documento");
		out.print(e2.getMessage());
	}

	}


}
